package com.shsun.curveservice.core.aspect;

import com.alibaba.fastjson2.JSON;
import com.shsun.curveservice.domain.entity.InterfaceLog;
import com.shsun.curveservice.logic.service.InterfaceLogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public  class  LoggingAspect  {

      private  static  final  Logger  logger  =  LoggerFactory.getLogger(LoggingAspect.class);
      @Resource
      private InterfaceLogService interfaceLogService;

      //  指定切点表达式
      @Pointcut("execution(*  com.shsun..controller..*(..))")
      public  void  controllerMethods()  {
      }

      //  环绕通知，在方法执行前后执行
      @Around("controllerMethods()")
      public  Object  logAround(ProceedingJoinPoint joinPoint)  throws  Throwable  {
            //  获取当前请求对象
            HttpServletRequest request  =  ((ServletRequestAttributes)  RequestContextHolder.getRequestAttributes()).getRequest();

            //  获取访问路径
            String  requestURI  =  request.getRequestURI();
            String method = request.getMethod();

            //  打印访问路径
            System.out.println("Access  Path:  "  +  requestURI);
            System.out.println("Access  Method:  "  +  method);



            //  获取方法入参
            Object[]  args  =  joinPoint.getArgs();
            System.out.println("Method:  "  +  joinPoint.getSignature().getName()  +  ",  Args:  "  +  java.util.Arrays.toString(args));

            //  执行方法
            Object  result  =  joinPoint.proceed();

            //  获取方法出参
            System.out.println("Method:  "  +  joinPoint.getSignature().getName()  +  ",  Return:  "  +  result);

            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setUrl(requestURI);
            interfaceLog.setMethod(method);
            interfaceLog.setParam(JSON.toJSONString(args));
            interfaceLog.setResult((String) result);
            interfaceLogService.save(interfaceLog);

            //  返回方法结果
            return  result;
      }
}
